/**
 * ConnectionKeepAliveStrategyImpl.java<br>
 * 
 * @author aaronwong.sd@foxmail.com
 * @version 下午3:11:46
 */
package com.iwechat.httpClient;

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;

import com.iwechat.PropertyUtils;

/**
 * 链接保活策略
 * 
 * @author aaronwong.sd@foxmail.com
 */
public class ConnectionKeepAliveStrategyImpl implements ConnectionKeepAliveStrategy {
    /*
     * (non-Javadoc)
     * 
     * @see org.apache.http.conn.ConnectionKeepAliveStrategy#getKeepAliveDuration(org.apache.http.HttpResponse, org.apache.http.protocol.HttpContext)
     */
    @Override
    public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
        // Honor 'keep-alive' header
        HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
        while (it.hasNext()) {
            HeaderElement he = it.nextElement();
            String param = he.getName();
            String value = he.getValue();
            if (value != null && param.equalsIgnoreCase("timeout")) {
                try {
                    return Long.parseLong(value) * 1000;
                } catch (NumberFormatException ignore) {
                }
            }
        }
        HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
        PropertyUtils util = PropertyUtils.getInstance();
        String domain = util.getStringValue("settings", "default.domain");
        int k1 = util.getIntValue("settings", "default.domain.keepAlive");
        int k2 = util.getIntValue("settings", "default.keepAlive");
        if (domain.equalsIgnoreCase(target.getHostName())) {
            return k1 * 1000;
        } else {
            return k2 * 1000;
        }
    }
}
